<template>
  <div>
    <!-- 查询条件 -->
    <el-form ref="searchForm" label-width="80px" :inline="true" size="small"
      style="margin-top: 20px; margin-left: 20px">
      <el-form-item>
        <el-input placeholder="请输入部门名称" v-model="searchModel.departmentName" @keyup.enter.native="fuzzySearch()">
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fuzzySearch()">查询</el-button>
        <el-button icon="el-icon-refresh-right" @click="resetValue()">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="openAddWindow()" v-if="hasPermission('sys:department:edit')">新增部门</el-button>
      </el-form-item>
    </el-form>
    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 95%; margin-bottom: 20px; margin-left: 20px" row-key="id"
      default-expand-all :tree-props="{ children: 'children' }">
      <el-table-column prop="departmentName" label="部门名称"></el-table-column>
      <el-table-column prop="parentName" label="所属部门"></el-table-column>
      <el-table-column prop="pid" label="所属部门编码"></el-table-column>
      <el-table-column prop="phone" label="部门电话"></el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit-outline" type="primary" size="small" @click="handleEdit(scope.row)" v-if="hasPermission('sys:department:edit')">编辑</el-button>
          <el-button icon="el-icon-close" type="danger" size="small" @click="handleDelete(scope.row)" v-if="hasPermission('sys:department:delete')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加和修改窗口 -->
    <systemDialog :title="deptDialog.title" :visible="deptDialog.visible" :width="deptDialog.width"
      :height="deptDialog.height" @onClose="onClose()" @onConfirm="onConfirm()">
      <div slot="content">
        <el-form :model="dept" ref="deptForm" :rules="rules" label-width="80px" :inline="true" size="small">
          <el-form-item label="所属部门" prop="parentName">
            <el-input v-model="dept.parentName" @click.native="selectDepartment()" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="dept.departmentName"></el-input>
          </el-form-item>
          <el-form-item label="部门电话">
            <el-input v-model="dept.phone"></el-input>
          </el-form-item>
          <el-form-item label="部门地址">
            <el-input v-model="dept.address"></el-input>
          </el-form-item>
          <el-form-item label="排序位次">
            <el-input v-model="dept.orderNum"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </systemDialog>
    <!-- 选择所属部门窗口 -->
    <systemDialog :title="parentDialog.title" :visible="parentDialog.visible" :width="parentDialog.width"
      :height="parentDialog.height" @onClose="onParentClose()" @onConfirm="onParentConfirm()">
      <!-- 选择所属部门窗口 -->
      <div slot="content">
        <el-tree ref="parentTree" :data="treeList" node-key="id" :props="defaultProps" :empty-text="null"
          :highlight-current="true" :default-expand-all="true" :expand-on-click-node="false"
          @node-click="handleNodeClick">
          <div class="customer-tree-node" slot-scope="{ node, data }">
            <!-- 当前节点是否有子节点 -->
            <span v-if="data.children.length === 0">
              <i class="el-icon-document"></i>
            </span>
            <!-- 当前节点有子节点 -->
            <span v-else @click="openBtn(data)">
              <svg-icon v-if="data.open" icon-class="add-s" />
              <svg-icon v-else icon-class="sub-s" />
            </span>
            <span style="margin-left: 5px">{{ node.label }}</span>
          </div>
        </el-tree>
      </div>
    </systemDialog>
  </div>
</template>
<script>
  import departmentApi from "@/api/department";
  import systemDialog from "@/components/System/systemDialog";
  export default {
    name: "department",
    components: {
      systemDialog,
    },
    data() {
      return {
        searchModel: {
          departmentName: "",
        },
        //response table data, in order to refresh the page
        respData: [],
        //the table data in view page, for search
        tableData: [],
        //部门窗口属性
        deptDialog: {
          title: "新增部门",
          visible: false, //是否显示
          width: 560,
          height: 170,
        },
        //部门对象
        dept: {
          id: "",
          pid: "", //父部门
          parentName: "", //父部门名称
          departmentName: "", //部门名称
          address: "", //地址
          phone: "", //电话
          orderNum: "", //序号
        },
        //表单验证规则
        rules: {
          parentName: [{
            required: true,
            trigger: "change",
            message: "请选择所属部门",
          }, ],
          departmentName: [{
            required: true,
            trigger: "blur",
            message: "请输入部门名称",
          }, ],
        },
        //选择所属部门
        parentDialog: {
          title: "选择所属部门",
          visible: false, //是否显示
          width: 300,
          height: 400,
        },
        treeList: [],
        //树形组件默认属性值
        defaultProps: {
          children: "children",
          label: "departmentName",
        },
      };
    },
    created() {
      this.search();
    },
    methods: {
      /**查询部门列表 */
      async search() {
        let res = await departmentApi.getDepartmentList();
        if (res.success) {
          this.respData = res.data;
          this.tableData = this.respData;
        }
      },
      // 模糊查询所包含的部门列表
      async fuzzySearch() {
        if (this.searchModel.departmentName === "") {
          this.search();
        } else {
          this.tableData = await this.handleTreeData(
            this.respData,
            this.searchModel.departmentName
          );
        }
      },
      // fuzzy search departmentName in respData
      handleTreeData(treeData, searchValue) {
        if (!treeData || treeData.length === 0) {
          return [];
        }
        const array = [];
        for (let i = 0; i < treeData.length; i += 1) {
          let match = false;
          /** fuzzy search departmentName */
          // departmentName is the key in tableData, return from json，大小写忽略
          match = treeData[i].departmentName
            .toLowerCase()
            .includes(searchValue.toLowerCase());

          /** fuzzy serach all keys */
          // for (let pro in treeData[i]) {
          //   console.log(treeData[i][pro])
          //   if (typeof (treeData[i][pro]) == 'string' ) {
          //     match = treeData[i][pro].includes(searchValue);
          //     if (match ) break;
          //   }
          // }
          if (
            this.handleTreeData(treeData[i].children, searchValue).length > 0 ||
            match
          ) {
            if (treeData[i].type == 0 && match) {
              this.flag = 0;
              searchValue = "";
              array.push({
                ...treeData[i],
                children: this.handleTreeData(treeData[i].children, searchValue),
              });
            } else if (treeData[i].type == 1 && match) {
              if (this.flag == 0) {
                this.flag = 1;
              }
              searchValue = "";
              array.push({
                ...treeData[i],
                children: this.handleTreeData(treeData[i].children, searchValue),
              });
              if (this.flag != 1) {
                searchValue = this.search;
              }
            } else {
              array.push({
                ...treeData[i],
                children: this.handleTreeData(treeData[i].children, searchValue),
              });
            }
          }
        }
        return array;
      },
      openAddWindow() {
        //清空表单
        this.$resetForm("deptForm", this.dept);
        //设置窗口标题
        this.deptDialog.title = "新增部门";
        //显示添加部门窗口
        this.deptDialog.visible = true;
      },
      // 窗口关闭
      onClose() {
        //关闭窗口
        this.deptDialog.visible = false;
      },
      // 窗口确认
      onConfirm() {
        //进行表单验证
        this.$refs.deptForm.validate(async (valid) => {
          //验证通过
          if (valid) {
            let res = null;
            //判断是新增还是修改
            if (this.dept.id === "") {
              //为空是新增
              res = await departmentApi.addDept(this.dept);
            } else {
              //修改
              res = await departmentApi.updateDept(this.dept);
            }
            //判断是否成功
            if (res.success) {
              this.$message.success(res.message);
              //刷新数据
              this.search();
            }
            this.deptDialog.visible = false;
          } else {
            this.$message.error(res.message);
          }
        });
      },

      //选择所属部门窗口打开
      async selectDepartment() {
        //显示窗口
        this.parentDialog.visible = true;
        //设置窗口标题
        this.parentDialog.title = "选择所属部门";
        //查询部门列表
        let res = await departmentApi.getParentTreeList();
        //判断是否成功
        if (res.success) {
          //赋值
          this.treeList = res.data;
        }
      },
      //树节点点击事件
      handleNodeClick(data) {
        //传输给创建窗口
        this.dept.pid = data.id;
        this.dept.parentName = data.departmentName;
      },
      //选择所属部取消事件
      onParentClose() {
        this.parentDialog.visible = false;
      },
      //选择所属部门确认事件
      onParentConfirm() {
        this.parentDialog.visible = false;
      },
      // 编辑部门
      handleEdit(row) {
        //数据回显
        this.$objCopy(row, this.dept);
        //设置窗口标题
        this.deptDialog.title = "编辑部门";
        //显示编辑部门窗口
        this.deptDialog.visible = true;
      },
      /**删除某个部门前，判断该部门是否存在子部门，
       * 如果存在子部门，则提示不能删除；
       * 判断该部门下是否存在用户，如果存在则不能删除。 */
      async handleDelete(row) {
        //查询部门下是否存在子部门或用户
        let result = await departmentApi.checkDepartment({
          id: row.id,
        });
        //判断是否可以删除
        if (!result.success) {
          //提示不能删除
          this.$message.warning(result.message);
        } else {
          //确认是否删除
          let confirm = await this.$myconfirm("确定要删除该数据吗?");
          if (confirm) {
            //发送删除请求
            let res = await departmentApi.deleteById({
              id: row.id,
            });
            //判断是否成功
            if (res.success) {
              //成功提示
              this.$message.success(res.message);
              //刷新
              this.search();
            } else {
              //失败提示
              this.$message.error(res.message);
            }
          }
        }
      },
      //重置查询
      resetValue() {
        this.searchModel.departmentName=''
        this.search()
      },
    },
  };

</script>
<style scoped>
</style>
